﻿import mx.utils.Delegate;

import com.mixmedia.display.ErrorDisplay;
import com.mixmedia.display.ProgressDisplay;
import com.mixmedia.mx.AbstractEventDispatcher;
import com.mixmedia.mx.Event;
import com.mixmedia.net.HTTPRequestQueue;
import com.mixmedia.net.ILoadStrategy;
import com.mixmedia.mx.events.LoaderEvent;

/**
 * @author colin
 */
class com.mixmedia.net.URLLoader extends AbstractEventDispatcher implements ILoadStrategy{
	public var strategy : ILoadStrategy;

	private var delLoad : Function;
	private var request : String;
	private var preloaderParent : MovieClip; 
	private var preloaderID : String;

	private var errorIconParent : MovieClip;
	private var errorIconID : String;
	
	private var queue:HTTPRequestQueue;

	public function URLLoader(strategy:ILoadStrategy,queueThreadId:Number){
		preloaderParent = _root;
		preloaderID = 'preloaderSystem';
		errorIconParent = preloaderParent;
		errorIconID = 'ErrorIcon';

		queue = HTTPRequestQueue.instance(queueThreadId);

		delLoad = Delegate.create(this,doLoad);
		this.strategy = strategy;
		strategy.addEventListener(Event.COMPLETE,Delegate.create(this,forwardEvent));
		strategy.addEventListener(Event.OPEN,Delegate.create(this,forwardEvent));
		strategy.addEventListener(Event.PROGRESS,Delegate.create(this,forwardEvent));

		strategy.addEventListener(Event.READY,Delegate.create(this,onReady));
		strategy.addEventListener(Event.ERROR,Delegate.create(this,onError));
		strategy.addEventListener(Event.COMPLETE,Delegate.create(this,onLoadComplete));
	}

	public function load(request:String):Void{
		this.request = request;
		queue.addRequest(delLoad);
	}

	public function post(request:String,postData:Object):Void{
		
	}

	public function getTarget():Object{
		return strategy.getTarget();
	}

	private function doLoad():Void{
		makePreloader();
		strategy.load(request);
	}

	private function forwardEvent(evt:LoaderEvent){
		dispatchEvent(evt);
	}
	
	private function onError(evt){
		ErrorDisplay.make(errorIconParent,errorIconID);
		killPreloader();
		queue.next();
		dispatchEvent(evt);
	}

	private function onReady(evt) : Void {
		killPreloader();
		dispatchEvent(evt);
	}

	private function makePreloader(){
		ProgressDisplay.make(preloaderParent,preloaderID,{target:getTarget()});
	}

	private function killPreloader(){
		ProgressDisplay.remove(preloaderParent);
	}
	
	public function setPreloader(mc:MovieClip,id:String){
		this.preloaderParent = mc;
		this.preloaderID = id;
	}
	
	public function setErrorIcon(mc:MovieClip,id:String){
		this.errorIconParent = mc;
		this.errorIconID = id;
	}

	private function onLoadComplete(evt:Event) : Void {
		killPreloader();
		queue.next();
		dispatchEvent(evt);
	}
}